package com.tianxin.workbao.workBao.dataProvide;

import android.content.Context;

import com.alibaba.fastjson.JSON;
import com.tianxin.workbao.workBao.R;
import com.tianxin.workbao.workBao.bean.Role;
import com.tianxin.workbao.workBao.bean.RoleDao;
import com.tianxin.workbao.workBao.bean.User;
import com.tianxin.workbao.workBao.bean.UserDao;
import com.tianxin.workbao.workBao.bean.UserroleKey;
import com.tianxin.workbao.workBao.bean.UserroleKeyDao;
import com.tianxin.workbao.workBao.bean.VUserRole;
import com.tianxin.workbao.workBao.common.Constant;
import com.tianxin.workbao.workBao.common.URL;
import com.tianxin.workbao.workBao.helper.GreenDaoHelper;
import com.tianxin.workbao.workBao.listener.UpdateListViewListener;
import com.tianxin.workbao.workBao.okhttp.CommonOkHttpClient;
import com.tianxin.workbao.workBao.okhttp.listener.DisposeDataHandle;
import com.tianxin.workbao.workBao.okhttp.listener.DisposeDataListener;
import com.tianxin.workbao.workBao.okhttp.request.CommonRequest;
import com.tianxin.workbao.workBao.okhttp.request.RequestParams;
import com.tianxin.workbao.workBao.utils.common.NetworkUtils;
import com.tianxin.workbao.workBao.utils.common.SPUtils;

import org.greenrobot.greendao.query.Query;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by hacker on 2017/6/19.
 */
public class RoleProvide extends BaseDataProvide {
    private List<Role> roleList;
    private UpdateListViewListener mUpdateListViewListener;
    private int mPage;
    private RoleDao roleDao;
    private boolean isUpdate = false;

    public RoleProvide(Context context, UpdateListViewListener listener) {
        super(context);
        this.mUpdateListViewListener = listener;
        roleDao = GreenDaoHelper.newInstance().getDaoSession().getRoleDao();
    }

    public List<Role> getRoleList() {
        return roleList;
    }

    public void getDatas(int page) {
        mPage = page;
        if (NetworkUtils.isConnected(mContext)) {
            mUpdateListViewListener.showProgress();
            Map<String, String> map = new HashMap<>();
            map.put(Constant.APPTOKEN_NAME, getAppToken());
            map.put("page", mPage + "");
            RequestParams params = new RequestParams(map);
            CommonOkHttpClient.post(CommonRequest.createPostRequest(URL.getRoleUrl(), params), getDisposeDataHandle());
        } else {
            mUpdateListViewListener.hideProgress();
            mUpdateListViewListener.showMessage(mContext.getResources().getString(R.string.poor_network) + " 获取本地数据");
            Query<Role> roleQuery = roleDao.queryBuilder().where(RoleDao.Properties.State.eq(1))
                    .offset((mPage - 1) + 12).limit(12).build();
            roleList = roleQuery.list();
            refreshUI();
        }
    }

    public void getDatasByUserid(long userid) {
        if (NetworkUtils.isConnected(mContext)) {
            mUpdateListViewListener.showProgress();
            Map<String, String> map = new HashMap<>();
            map.put(Constant.APPTOKEN_NAME, getAppToken());
            map.put("userid", userid + "");
            RequestParams params = new RequestParams(map);
            CommonOkHttpClient.post(CommonRequest.createPostRequest(URL.getRolesByUseridUrl(), params), getDisposeDataHandle());
        } else {
            mUpdateListViewListener.hideProgress();
            mUpdateListViewListener.showMessage(mContext.getResources().getString(R.string.poor_network));
            refreshUI();
        }
    }


    /**
     * 真正处理返回数据
     *
     * @param responseObj
     */
    private void handleResponseObj(Object responseObj) {
        try {
            JSONObject jsonObject = new JSONObject(responseObj.toString());
            int status = jsonObject.getInt(Constant.RESPONSE_STATUS);
            if (status > 0) {
                if (isUpdate) {
                    VUserRole vUserRole = JSON.parseObject(jsonObject.getJSONObject(Constant.RESPONSE_DATA).toString(), VUserRole.class);
                    if (vUserRole != null) {
                        List<User> users = vUserRole.getUsers();
                        if (!users.isEmpty()) {
                            deleteAllUser();
                            for (int i = 0; i < users.size(); i++) {
                                mGreenDaoHelper.getDaoSession().getUserDao().insert(users.get(i));
                            }
                        } else {
                            return;
                        }
                        List<Role> roles = vUserRole.getRoles();
                        if (!roles.isEmpty()) {
                            deleteAllRole();
                            for (int i = 0; i < roles.size(); i++) {
                                mGreenDaoHelper.getDaoSession().getRoleDao().insert(roles.get(i));
                            }
                        } else {
                            return;
                        }
                        List<UserroleKey> userroleKeys = vUserRole.getUserroleKeys();
                        if (!userroleKeys.isEmpty()) {
                            deleteAllUserRole();
                            for (int i = 0; i < userroleKeys.size(); i++) {
                                mGreenDaoHelper.getDaoSession().getUserroleKeyDao().insert(userroleKeys.get(i));
                            }
                        } else {
                            return;
                        }
                        mUpdateListViewListener.onRefreshData(roles.get(0));
                    } else {
                        mUpdateListViewListener.showMessage("更新失败");
                    }
                    return;
                }
                if (jsonObject.getJSONArray(Constant.RESPONSE_DATA) == null) {
                    mUpdateListViewListener.showMessage(jsonObject.getString(Constant.RESPONSE_INFO));
                    return;
                }
                if (roleList != null && !roleList.isEmpty()) {
                    roleList.clear();
                }
                roleList = JSON.parseArray(jsonObject.getString(Constant.RESPONSE_DATA).toString(), Role.class);
                refreshUI();
                saveToDb();
            } else {
                mUpdateListViewListener.showMessage(mContext.getResources().getString(R.string.no_data));
            }
        } catch (JSONException e) {
            showRequestErrorMessage(mUpdateListViewListener, responseObj.toString());
            e.printStackTrace();
        }
    }

    private void deleteAllUser() {
        UserDao userDao = mGreenDaoHelper.getDaoSession().getUserDao();
        userDao.deleteAll();
    }

    private void deleteAllRole() {
        roleDao.deleteAll();
    }

    private void deleteAllUserRole() {
        UserroleKeyDao userroleKeyDao = mGreenDaoHelper.getDaoSession().getUserroleKeyDao();
        userroleKeyDao.deleteAll();
    }

    private void saveToDb() {
        if (roleList == null || roleList.isEmpty()) {
            return;
        }
        for (Role role : roleList) {
            roleDao.insertOrReplace(role);
        }
    }

    @Override
    public DisposeDataHandle getDisposeDataHandle() {
        if (disposeDataHandle == null) {
            disposeDataHandle = new DisposeDataHandle(getDisposeDataListener());
        }
        return disposeDataHandle;
    }

    @Override
    public DisposeDataListener getDisposeDataListener() {
        if (disposeDataListener == null) {
            disposeDataListener = new DisposeDataListener() {
                @Override
                public void onSuccess(Object responseObj) {
                    mUpdateListViewListener.hideProgress();
                    if (responseObj.equals(null)) {
                        mUpdateListViewListener.showMessage(mContext.getResources().getString(R.string.no_response));
                    } else {
                        handleResponseObj(responseObj);
                    }
                }

                @Override
                public void onFailure(Object reasonObj) {
                    mUpdateListViewListener.hideProgress();
                    showRequestErrorMessage(mUpdateListViewListener, reasonObj.toString());
                }
            };
        }
        return disposeDataListener;
    }


    @Override
    public void refreshUI() {
        if (mPage > 1) {
            mUpdateListViewListener.onLoadMoreData(roleList);
        } else {
            mUpdateListViewListener.onRefreshData(roleList);
        }
    }

    public void search(String query) {

    }

    /**
     * update role and userRole
     */
    public void updateRole() {
        isUpdate = true;
        if (NetworkUtils.isConnected(mContext)) {
            mUpdateListViewListener.showProgress();
            Map<String, String> map = new HashMap<>();
            map.put(Constant.APPTOKEN_NAME, getAppToken());
            RequestParams params = new RequestParams(map);
            CommonOkHttpClient.post(CommonRequest.createPostRequest(URL.getUpdateRoleUrl(), params), getDisposeDataHandle());
        } else {
            mUpdateListViewListener.showMessage(mContext.getResources().getString(R.string.poor_network));
        }
    }

    public boolean hasRole(String roleName) {
        long userId = SPUtils.getPrefLong(Constant.CURRENT_USER_ID, 0);
        if (userId == 0 || roleName.length() == 0) {
            return false;
        }
        Query<Role> roleQuery = roleDao.queryBuilder().where(RoleDao.Properties.State.eq(1))
                .where(RoleDao.Properties.Rolekey.eq(roleName)).limit(1).build();
        List<Role> roleList = roleQuery.list();
        if (roleList.isEmpty()) {
            return false;
        }
        long roleID = roleList.get(0).getId();
        UserroleKeyDao userroleKeyDao = mGreenDaoHelper.getDaoSession().getUserroleKeyDao();
        Query<UserroleKey> userroleKeyQuery = userroleKeyDao.queryBuilder()
                .where(UserroleKeyDao.Properties.Userid.eq(userId))
                .where(UserroleKeyDao.Properties.Roleid.eq(roleID))
                .limit(1).build();
        List<UserroleKey> userroleKeyList = userroleKeyQuery.list();
        if (userroleKeyList != null && !userroleKeyList.isEmpty()) {
            return true;
        }
        return false;
    }
}
